//
//  CommentViewController.m
//  QSBK
//
//  Created by Eric Wang on 4/22/15.
//  Copyright (c) 2015 Eric Wang. All rights reserved.
//
#import "AppDelegate.h"
#import "Common.h"
#import "CommentCell.h"
#import "User.h"
#import "Comment.h"
#import "CommentFrame.h"
#import "AFNetworking.h"
#import "CommentViewController.h"
@interface CommentViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate>
{
    NSMutableArray *_commentFrameArray;
}
@property (strong, nonatomic)  UITextView *textView;
- (void)sendComment:(UIButton *)sender;
@property (strong, nonatomic)  UIButton *sendComment;
@property (strong, nonatomic)  UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
- (IBAction)back:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *tabView;

@end

@implementation CommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSubviews];
    [self getDataWithBlogID:self.headCell.blogFrame.blog.article_id];
    // Do any additional setup after loading the view from its nib.
}

- (void)setSubviews
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(keyBoardDisappear:) name:UIKeyboardWillHideNotification object:nil];
    
    _commentFrameArray = [[NSMutableArray alloc]init];
    self.titleLabel.text = [NSString stringWithFormat:@"糗事%d",[self.headCell.blogFrame.blog.article_id intValue]];
    
    self.tabView.delegate = self;
    self.tabView.dataSource = self;
    self.tabView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0,-30, ScreenW, 2)];
    self.tabView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 8)];
    self.tabView.tableHeaderView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    self.tabView.tableFooterView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    self.tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.textView.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1.0];
    self.textView.delegate = self;
    
    
    self.bottomView = [[UIView alloc]init];
    self.bottomView.frame = CGRectMake(0, ScreenH-40, ScreenW, 40);
    self.bottomView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.bottomView];
    [self.view bringSubviewToFront:self.bottomView];
    
    
    
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(20, 0, 180, 40)];
    [self.textView setTextColor:[UIColor colorWithRed:200/255.0 green:200/255.0 blue:200/255.0 alpha:1.0]];
    self.textView.delegate = self;
    self.textView.text = @"说点什么吧。。。";
    self.textView.font = [UIFont systemFontOfSize:17];
    [self.bottomView addSubview:self.textView];
    
    self.sendComment = [[UIButton alloc]initWithFrame:CGRectMake(ScreenW-40, 5, 30, 30)];
    [self.sendComment setImage:[UIImage imageNamed:@"ic_send.png"] forState:UIControlStateNormal];
    
    [self.sendComment addTarget:self action:@selector(sendComment:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.sendComment];
}

- (IBAction)back:(id)sender {
    [self.textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

//tableView delegate and dataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentFrameArray.count+1;;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==0)
    {
        return self.headCell;
    }else{
        
        CommentCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cell"];
        if(cell ==nil)
        {
            cell = [[CommentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            
        }
        
        cell.commentFrame = _commentFrameArray[indexPath.row-1];
        [cell setFloor:indexPath];
        return cell;
    }
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.textView resignFirstResponder];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
    return self.headCell.blogFrame.cellHeight;
    }else{
        return ((CommentFrame *)_commentFrameArray[indexPath.row-1]).cellHeight;
    }
}

-(void)getDataWithBlogID:(NSNumber *)str
{
    
    NSString *urlString = @"http://localhost:8888/thinkphp_3.2.3/Home/QSBK/getcomments";
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *dic = @{@"page":@0,@"article_id":str};
    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation,id responseObject){
        NSDictionary *responseDic = (NSDictionary *)responseObject;
        NSLog(@"%@",responseObject);
        NSArray *array = [responseDic objectForKey:@"comment"];
        
                for(NSDictionary *dic in array)
                {
                    User *user = [[User alloc]init];
                    Comment *comment = [[Comment alloc]init];
                    user.user_id = [dic objectForKey:@"user_id"];
                    user.articleTotal = [dic objectForKey:@"total"];
                    user.stater = [dic objectForKey:@"stater"];
                    user.role = [dic objectForKey:@"role"];
                    user.longitude = [dic objectForKey:@"longitude"];
                    user.latitude = [dic objectForKey:@"latitude"];
                    user.login = [dic objectForKey:@"login"];
                    user.last_visited_at = [dic objectForKey:@"last_visited"];
                    user.last_device = [dic objectForKey:@"last_device"];
                    user.icon = [dic objectForKey:@"icon"];
                    user.email = [dic objectForKey:@"email"];
                    comment.user = user;
                    comment.content = [dic objectForKey:@"comment_content"];
                    comment.comment_id = [dic objectForKey:@"comment_id"];
                    CommentFrame *commentFrame = [[CommentFrame alloc]init];
                    commentFrame.comment = comment;
        
                    [_commentFrameArray addObject:commentFrame];
                }

                dispatch_async(dispatch_get_main_queue(), ^{
        
                    [self.tabView reloadData];
        
                });
        
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
        
        
    }];
    
    

}
- (void)sendComment:(UIButton *)button {
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    if(delegate.user==nil)
    {
        [self dismissViewControllerAnimated:NO completion:^{
            if(self.delegate!=nil&&[self.delegate respondsToSelector:@selector(needLoginBeforeComment)])
            {
                [self.delegate needLoginBeforeComment];
            }
        }];
    }else{
        if(self.textView.text!=nil&&![self.textView.text isEqualToString:@""])
        {
            NSString *urlString = @"http://localhost:8888/thinkphp_3.2.3/Home/QSBK/comment?";
            NSDictionary *para = @{@"user_id":delegate.user.user_id,@"article_id":self.headCell.blogFrame.blog.article_id,@"comment_content":self.textView.text};
            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
           [manager POST:urlString parameters:para success:^(AFHTTPRequestOperation *operation,id responseObject){
            NSDictionary *dic = (NSDictionary *)responseObject;
            if([[dic objectForKey:@"err"] isEqualToString:@"0"])
            {
                
            }
            
            }failure:^(AFHTTPRequestOperation *operation,NSError *error)
            {
            NSLog(@"%@",error);
            }];
        }else{
        
        }
    }
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.textView.text = @"";
    return YES;
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    self.textView.text = @"说点什么吧。。。";
}
- (void)textViewDidChange:(UITextView *)textView
{
    if(![self.textView.text isEqualToString:@""])
    {
    [self.sendComment setImage:[UIImage imageNamed:@"ic_send_enable.png"] forState:UIControlStateNormal];
    }else{
        [self.sendComment setImage:[UIImage imageNamed:@"ic_send.png"] forState:UIControlStateNormal];
    }
}

-(void)keyBoardAppear:(NSNotification *)aNotification
{
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.bottomView.frame = CGRectMake(0, ScreenH-height-40, ScreenW  , 40);

        [self.view bringSubviewToFront:self.bottomView];
    }];
    
}

-(void)keyBoardDisappear:(NSNotification *)aNotification
{
    [UIView animateWithDuration:0.25 animations:^{
        self.bottomView.frame = CGRectMake(0, ScreenH-40, ScreenW, 40);
        [self.view bringSubviewToFront:self.bottomView];
    }];
    
}
@end
